package com.senseuni.da

import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import android.os.Environment
import android.util.DisplayMetrics
import com.elvishew.xlog.LogConfiguration
import com.elvishew.xlog.LogLevel
import com.elvishew.xlog.XLog
import com.elvishew.xlog.flattener.ClassicFlattener
import com.elvishew.xlog.printer.AndroidPrinter
import com.elvishew.xlog.printer.file.FilePrinter
import com.elvishew.xlog.printer.file.backup.NeverBackupStrategy
import com.elvishew.xlog.printer.file.clean.FileLastModifiedCleanStrategy
import com.elvishew.xlog.printer.file.naming.DateFileNameGenerator
import com.jakewharton.threetenabp.AndroidThreeTen
import com.senseuni.da.db.AppDatabase
import com.senseuni.da.utils.AppUtils
import com.senseuni.da.worker.AppLog
import com.tencent.bugly.crashreport.CrashReport
import com.tencent.mmkv.MMKV


class MyApplication : Application() {

    companion object{
        lateinit var app:Application
        @SuppressLint("StaticFieldLeak")
        lateinit var context: Context
        var DEVICE_ID:String = ""
        var mqttHost: String = ""
    }

    override fun onCreate() {
        super.onCreate()

        app = this
        context = applicationContext

        initLogger()
        AppDatabase.getInstance()

        CrashReport.initCrashReport(applicationContext)

        val mmkvRootDir = MMKV.initialize(this);
        XLog.d("MMKV Root Dir:%s", mmkvRootDir)

//        adjustDensity()

        AppUtils.saveBootTimes()

        initData()

        AppLog.instance.init()

//        TrueTime.build()
//            .withNtpHost("ntp1.aliyun.com")
//            .withLoggingEnabled(true)
//            .initialize()

        AndroidThreeTen.init(this)
    }

    private fun initLogger(){
        val logDir = Environment.getExternalStorageDirectory().absolutePath + "/lumx/logs"
        val filePrinter: FilePrinter = FilePrinter.Builder(logDir) // 指定保存日志文件的路径
            .fileNameGenerator(DateFileNameGenerator()) // 指定日志文件名生成器，默认为 ChangelessFileNameGenerator("log")
            .backupStrategy(NeverBackupStrategy()) // 指定日志文件备份策略，默认为 FileSizeBackupStrategy(1024 * 1024)
            .cleanStrategy(FileLastModifiedCleanStrategy(30 * 24 * 60 * 60 * 1000L)) // 指定日志文件清除策略，默认为 NeverCleanStrategy()
            .flattener(ClassicFlattener()) // 指定日志平铺器，默认为 DefaultFlattener
            .build()
//        Logger.addLogAdapter(DiskLogAdapter())
        
        val config = LogConfiguration.Builder()
            .logLevel(LogLevel.ALL)
            .tag("senseuni")
//            .enableThreadInfo()
            .build()
        val androidPrinter = AndroidPrinter()
        XLog.init(config, androidPrinter,filePrinter);
    }

    private fun initData() {
        DEVICE_ID = AppUtils.getDeviceId()
//        DEVICE_ID = "1c000c59b70048526dc"
//        DEVICE_ID = "36753562"
    }

    private fun adjustDensity() {
        val metrics = resources.displayMetrics
        val targetDensity = calculateTargetDensity(metrics)

        // 更新density和scaledDensity
        metrics.density = targetDensity
        metrics.scaledDensity = targetDensity * (metrics.scaledDensity / metrics.density)
        metrics.densityDpi = (targetDensity * 160).toInt()

        // 如果需要重置字体缩放，请取消注释以下行
        // val config = Configuration(resources.configuration)
        // config.fontScale = 1.0f
        // createConfigurationContext(config)
    }

    private fun calculateTargetDensity(metrics: DisplayMetrics): Float {
        // 设计稿的基准宽度（以px为单位）
        val baseWidthPx = 1280f

        // 当前屏幕的实际宽度（以px为单位）
        val screenWidthPx = metrics.widthPixels.toFloat()

        // 计算缩放因子，使得当前屏幕宽度与设计稿宽度相匹配
        val scaleFactor = screenWidthPx / baseWidthPx

        // 目标density应该是原始density乘以缩放因子
        return metrics.density * scaleFactor
    }

}